import {browserHistory} from 'react-router'


export function saveUserInfoToLocal(userInfo) {
    if(!userInfo) return false;
    saveDataToLocal('token', userInfo.token);
    saveDataToLocal('name', userInfo.phone);
}

export function saveDataToLocal(key, data) {
    window.localStorage[key] = JSON.stringify(data);
}

export function getDataFromLocal(str) {
    var  val =  window.localStorage[str];
    return val ? JSON.parse(val) : undefined;
}

export function isLogin(){
    const token = getDataFromLocal('token') || "";
    return !!token;
}

export function expires(refresh) {
    localStorage.clear();
    let referer = location.pathname+location.search;
    if(refresh) location.reload();
}

export function loginRequired(next, replace) {
    if(isLogin()) return true;
    let referer = location.pathname+location.search;
    //当前已经是登录页面
    if(location.pathname === '/user/login')return;
    replace({pathname: '/user/login', query: {referer}});
}

export function unLoginRequired(next, replace) {
    if(!isLogin()) return true;
    replace({pathname: '/manage'});
}

/**
 * 去登录页面,而且带上当前页面地址作为referer,登录完成后将会跳回来
 */
export function refererLogin(){
    let referer = location.pathname+location.search;
    //当前已经是登录页面
    if(location.pathname === '/user/login')return;
    browserHistory.replace({pathname: '/user/login', query: {referer}});
}

function gCacheData(str) {
    var val = window.sessionStorage[str];
    val = val ? val : window.localStorage[str];
    return val ? JSON.parse(val) : '';
}
//合并Required方法
export function $() {
    return (n, r) => {
        for(var f of arguments){
            if(!f(n,r))return;
        }
    }
}
